package com.hay.oss.local;

import com.hay.oss.OssConstant;
import com.hay.oss.OssTemplate;
import com.hay.oss.bo.OssFile;
import com.hay.oss.util.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author LiMouRen
 * @date 2023/7/26
 */
@Slf4j
public class LocalOssTemplate implements OssTemplate {

    private final LocalOssProperties ossProperties;

    /**
     * 存储位置
     */
    private final String bucketName;

    public LocalOssTemplate(LocalOssProperties ossProperties){
        this.ossProperties = ossProperties;
        bucketName = ossProperties.getBucketName();
    }

    /**
     * 上传文件
     * @param category 文件前缀,如 product/20240115
     * @param originalFileName 文件原名
     * @param inputStream 输入流
     * @param useOriginalName true 使用原名
     */
    @Override
    public OssFile uploadFile(String category, String originalFileName, InputStream inputStream, Boolean useOriginalName){
        String relativeUrl = createRelativeUrl(category,originalFileName,useOriginalName);
        String fileAbsolutePath = bucketName + OssConstant.SLASH + relativeUrl;
        FileUtil.createFile(fileAbsolutePath,inputStream);
        String link = ossProperties.getProxyPrefix() + relativeUrl;
        OssFile ossFile = new OssFile();
        ossFile.setLink(link);
        ossFile.setOriginalName(originalFileName);
        ossFile.setRelativeUrl(relativeUrl);
        return ossFile;
    }

    @Override
    public InputStream getInputStream(String relativeUrl) {
        String fileAbsolutePath = this.bucketName + OssConstant.SLASH + relativeUrl;
        File file = new File(fileAbsolutePath);
        if (!file.exists()){
            throw new RuntimeException("文件不存在");
        }
        try{
            return new BufferedInputStream(Files.newInputStream(Paths.get(fileAbsolutePath)));
        }catch (Exception e){
            log.error("getInputStream relativeUrl:{}, error:{},",relativeUrl,e.getMessage(),e);
            throw new RuntimeException("获取本地文件流失败 "+e.getMessage());
        }
    }

    /**
     * 删除文件
     * @param relativeUrl 相对地址，如 product/20240115/1.jpg
     */
    @Override
    public void removeFile(String relativeUrl){
        String fileAbsolutePath = bucketName + OssConstant.SLASH + relativeUrl;
        FileUtil.deletedFile(fileAbsolutePath);
    }

}


